//
//  UIScrollView+MLKit.m
//  Pods
//
//  Created by molon on 15/6/25.
//
//

#import "UIScrollView+MLKit.h"
#import "UIView+MLKit.h"
#import "MLRuntime.h"

@implementation UIScrollView (MLKit)

- (void)adjustContentInsetTop:(CGFloat)top andBottom:(CGFloat)bottom
{
    UIEdgeInsets inset = self.contentInset;
    if (inset.top==top&&inset.bottom==bottom) {
        return;
    }
    
    inset.top = top;
    inset.bottom = bottom;
    
    CGFloat adjustOffsetY = self.contentInset.top - inset.top;
    CGPoint offset = self.contentOffset;
    self.contentInset = inset;
    
    offset.y += adjustOffsetY;
    self.contentOffset = offset;
}

- (void)adjustContentInsetBottom:(CGFloat)bottom
{
    UIEdgeInsets inset = self.contentInset;
    if (inset.bottom==bottom) {
        return;
    }
    
    inset.bottom = bottom;
    self.contentInset = inset;
}

- (CGFloat)bottomContentOffset
{
    CGFloat offsetY = self.contentSize.height+self.contentInset.bottom-self.frameHeight;
    offsetY = MAX(offsetY, -self.contentInset.top);
    return offsetY;
}


- (void)scrollToTopWithAnimated:(BOOL)animated
{
    [self scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:animated];
}

- (void)scrollToBottomWithAnimated:(BOOL)animated
{
    [self setContentOffset:CGPointMake(0, [self bottomContentOffset]) animated:animated];
}


- (void)scrollToVerticalMiddleWithRect:(CGRect)rect animated:(BOOL)animated
{
    CGFloat height = self.frameHeight;
    CGFloat adjustOriginY = MAX(rect.origin.y+rect.size.height/2-height/2,-self.contentInset.top);
    if (adjustOriginY>self.contentSize.height+self.contentInset.bottom-height) {
        adjustOriginY = self.contentSize.height+self.contentInset.bottom-height;
    }
    adjustOriginY = MAX(adjustOriginY, -self.contentInset.top);
    //让选中的滚动到中间位置
    [self setContentOffset:CGPointMake(0, adjustOriginY) animated:animated];
}

#pragma mark - scrollIndicatorInsets follow contentInset
- (void)__hookSetContentInset:(UIEdgeInsets)contentInset
{
    [self __hookSetContentInset:contentInset];
    
    self.scrollIndicatorInsets = contentInset;
}

+ (void)load
{
    Swizzle([self class], @selector(setContentInset:), @selector(__hookSetContentInset:));
}

@end
